<template>
  <a-card style="width: 100%">
    <div class="header">
      <a-space class="left" direction="vertical" :size="[8, 12]">
        <Condition
          :condition="condition"
          :btns="['reset']"
          @search="onSearch"
          @reset="conditionReset"
        />
        <div class="title">共筛选出 {{ pagination.total }} 条数据</div>
      </a-space>
      <a-space class="right" direction="vertical" :size="[8, 12]">
        <a-input-search
          v-model:value="questionnaireName"
          placeholder="请输入健康随访名称"
          style="width: 220px"
          @search="onSearch"
        />
        <!-- <a-input class="input" placeholder="请输入管理方案名称"></a-input> -->
        <a-button type="primary" @click="modalShow">新建问卷</a-button>
      </a-space>
    </div>
    <div class="main">
      <a-table
        class="table"
        size="small"
        :loading="loading"
        :dataSource="List"
        :columns="columns"
        :pagination="pagination"
        @change="paginationChange"
        :sticky="{ offsetHeader: 0 }"
      >
        <template #bodyCell="{ column, text, index, record }">
          <template v-if="column.dataIndex === 'no'">
            {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
          </template>
          <template v-else-if="column.dataIndex === 'questionnaireType'">
            {{ record.questionnaireType === 'scale' ? '量表问卷' : '普通问卷' }}
          </template>
          <!-- <template v-else-if="column.dataIndex === 'managePath'">
            <div class="tags" v-if="record[column.dataIndex]">
              <a-tag
                type="parmary"
                :title="item"
                v-for="(item, i) in record[column.dataIndex].split(', ')"
                :key="i"
                >{{ item }}</a-tag
              >
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'createTime'">
            {{ timeFilter(record[column.dataIndex]) }}
          </template> -->
          <template v-else-if="column.dataIndex === 'action'">
            <a-button type="link" @click="modalShow2(record)">查看详情</a-button>
            <a-button type="link" @click="modalShow3(record)">设置规则</a-button>
            <a-button type="link" @click="sortShow(record)">排序</a-button>
            <a-button
              type="link"
              @click="delForm(record)"
              :disabled="record.managePath ? true : false"
              >删除表单</a-button
            >
          </template>
          <template v-else>
            {{ text }}
          </template>
        </template>
      </a-table>
    </div>
    <a-modal
      width="720px"
      :bodyStyle="store.userStore.bodyStyle"
      v-model:open="modal2.open"
      :title="modal2.title"
      ok-text="确认"
      :maskClosable="false"
    >
      <div class="modal-content" style="min-height: 400px">
        <a-form
          class="modelForm"
          ref="modelForm2"
          :model="formData"
          :colon="false"
          :label-col="{ style: { width: '60px' } }"
          labelAlign="left"
        >
          <!-- <a-form-item label="模板类型" name="templateAffiliation"  v-if="modal.type != 'detail'">
          <a-select v-model:value="formState.templateAffiliation" :disabled="true">
            <a-select-option label="公共模板" value="公共模板"> 公共模板 </a-select-option>
            <a-select-option label="个人模板" value="个人模板"> 个人模板 </a-select-option>
          </a-select>
        </a-form-item> -->
          <a-form-item>
            <span class="title">{{ formData.questionnaireName }}</span>
          </a-form-item>
        </a-form>
        <t-form :formData="formData.content" :condition="true" />
      </div>
      <template #footer>
        <a-button @click="modal2Cancel" :disabled="!modal2.allowUpdate">编辑</a-button>
        <a-button key="submit" type="primary" @click="modal2.open = false">确认</a-button>
      </template>
    </a-modal>
    <rule ref="ruleRef" @onConfirm="ruleConfirm" />
    <sort ref="sortRef" @onConfirm="sortConfirm" />
    <form-modal ref="formRef" @onConfirm="formConfirm" />
  </a-card>
</template>

<script lang="ts" setup name="健康随访">
import { ref, reactive, onMounted } from 'vue'
import IconFont from '@/components/IconFont/index.vue'
import Condition from '@/components/Condition/index.vue'
import TForm from '@/components/TForm/index.vue'
import { h, createVNode } from 'vue'
import { PlusOutlined, ExclamationCircleFilled } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { timeFilter } from '@/utils/tools'
import { numberToChinese, parseTime } from '@/utils/tools'
import {
  getTemplateQuestionList,
  TemplateQuestionAdd,
  TemplateQuestionUpdate,
  TemplateQuestionDel
} from '@/api/template'
import { useDict } from './components/getDict'
import store from '@/store'
import _ from 'lodash'
import Rule from './components/rule.vue'
import Sort from './components/sort.vue'
import FormModal from './components/formModal.vue'
const questionnaireName = ref('')
const questionnaireType = ref('')
const { creatorList, manageList, init } = useDict('健康随访')

const sorts = [
  'A',
  'B',
  'C',
  'D',
  'E',
  'F',
  'G',
  'H',
  'I',
  'J',
  'K',
  'L',
  'M',
  'N',
  'O',
  'P',
  'Q',
  'R',
  'S',
  'T',
  'U',
  'V',
  'W',
  'X',
  'Y',
  'Z'
]

const condition = ref([
  {
    title: '创建者',
    dataIndex: 'creator',
    type: 'select',
    value: '',
    data: creatorList
  },
  {
    title: '已配置管理路径',
    dataIndex: 'manageId',
    type: 'select',
    value: '',
    data: manageList
  },
  {
    title: '模板类型',
    dataIndex: 'questionnaireType',
    type: 'select',
    value: '',
    data: [
      {
        value: '',
        label: '全部'
      },
      {
        value: 'scale',
        label: '量表问卷'
      },
      {
        value: 'normal',
        label: '普通问卷'
      }
    ]
  }
])
const conditionReset = () => {
  pagination.current = 1
  init()
  condition.value.map((v) => {
    v.value = ''
  })
  getList()
}

const pagination = reactive({
  current: 1,
  total: 0,
  pageSize: 10,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100']
})

const columns = ref([
  {
    title: '序号',
    dataIndex: 'no',
    key: 'no',
    align: 'left',
    width: '50px'
  },
  {
    title: '健康随访名称',
    dataIndex: 'questionnaireName',
    key: 'questionnaireName',
    align: 'left'
  },
  {
    title: '问卷id',
    dataIndex: 'questionnaireId',
    key: 'questionnaireId',
    align: 'left'
  },
  {
    title: '模板类型',
    dataIndex: 'questionnaireType',
    key: 'questionnaireType',
    align: 'left'
    // width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'left',
    width: '200px'
  },
  //   {
  //     title: '创建者',
  //     dataIndex: 'creator',
  //     key: 'creator',
  //     align: 'left'
  //   },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'left',
    width: '200px'
  }
])

const loading = ref(false)
const List = ref([])

const getList = () => {
  loading.value = true
  const { current, pageSize } = pagination
  const obj = condition.value.reduce((c, v) => {
    if (v.value || v.value === 0) {
      return Object.assign(c, { [v.dataIndex]: v.value })
    } else {
      return c
    }
  }, {})
  const params = {
    page: current,
    limit: pageSize,
    questionnaireName: questionnaireName.value,
    questionnaireType: questionnaireType.value,
    ...obj
  }
  getTemplateQuestionList(params)
    .then((res) => {
      loading.value = false
      if (res.data.total > 0 && !res.data.list.length) {
        pagination.current = pagination.current - 1
        getList()
      } else {
        pagination.total = res.data.total
        List.value = res.data.list
      }
    })
    .catch((e) => {
      loading.value = false
    })
}

const paginationChange = (p) => {
  Object.assign(pagination, p)
  getList()
}

const onSearch = () => {
  pagination.current = 1
  getList()
}

onMounted(() => {
  // const str = []

  // str.map((v, index) => {
  //   v.id = sorts[index]
  //   v.list.map((u, index) => {
  //     u.id = v.id + '-' + (index + 1)
  //   })
  // })

  // console.log(JSON.stringify(str))

  getList()
})

const formRef = ref(null)

const modalShow = () => {
  formRef.value?.init()
}

const formConfirm = ({ data, success, fail, type }) => {
  const content = _.cloneDeep(data.content)
  content.map((v) => {
    v.list.map((u) => {
      if (u.type.includes('多')) {
        u['value'] = []
        u['sort'] = []
      } else {
        u['value'] = ''
        u['sort'] = ''
      }
      u['inputText'] = ''
      if (u.type.includes('选')) {
        u.options.map((w) => {
          w['label'] = w.value
          w['disabled'] = false
        })
      }
    })
  })
  // 表单校验通过
  const params = {
    ...data,
    content: JSON.stringify(convert(content, true)),
    platformId: store.userStore.platformId
  }

  if (type === 'save') {
    TemplateQuestionAdd(params)
      .then((res) => {
        message.success('新建成功')
        success()
        init()
        getList()
      })
      .catch((e) => {
        console.log(e)
        fail()
      })
  } else {
    TemplateQuestionUpdate(params)
      .then((res) => {
        message.success('编辑成功')
        success()
        init()
        getList()
      })
      .catch((e) => {
        console.log(e)
        fail()
      })
  }
}

const modal2 = reactive({
  title: '健康随访详情',
  allowUpdate: false,
  open: false
})

const formData = ref()
const modelForm2 = ref(null)

const modalShow2 = (item) => {
  modelForm2.value?.clearValidate()
  const { id, questionnaireName, questionnaireType, content, managePath } = item

  const obj = {
    id,
    questionnaireName: questionnaireName,
    questionnaireType: questionnaireType,
    content: convert(JSON.parse(content), false)
  }

  modal2.allowUpdate = managePath ? false : true
  formData.value = obj
  modal2.open = true
}

const ruleRef = ref(null)

const modalShow3 = (item) => {
  const { id, questionnaireName, questionnaireType, content, managePath } = item

  const obj = {
    id,
    questionnaireName: questionnaireName,
    questionnaireType: questionnaireType,
    content: convert(JSON.parse(content), false)
  }

  ruleRef.value.init(obj)
}

const ruleConfirm = ({ data, success, fail }) => {
  console.log(data, success, fail)
  const Data = _.cloneDeep(data)

  const params = {
    ...Data,
    content: JSON.stringify(convert(Data.content, true)),
    platformId: store.userStore.platformId
  }

  TemplateQuestionUpdate(params)
    .then((res) => {
      success()
      message.success('提交成功')
      init()
      getList()
      // modal3.loading = false
      // modal3.open = false
    })
    .catch((e) => {
      fail()
      // modal3.loading = false
      console.log(e)
    })
}

const sortRef = ref(null)

const sortShow = (item) => {
  const { id, questionnaireName, questionnaireType, content, managePath } = item

  const obj = {
    id,
    questionnaireName: questionnaireName,
    questionnaireType: questionnaireType,
    content: convert(JSON.parse(content), false)
  }

  sortRef.value.init(obj)
}

const sortConfirm = ({ data, success, fail }) => {
  console.log(data, success, fail)
  const Data = _.cloneDeep(data)

  const params = {
    ...Data,
    content: JSON.stringify(convert(Data.content, true)),
    platformId: store.userStore.platformId
  }

  TemplateQuestionUpdate(params)
    .then((res) => {
      success()
      message.success('提交成功')
      init()
      getList()
    })
    .catch((e) => {
      fail()
      console.log(e)
    })
}

const delForm = (item) => {
  Modal.confirm({
    title: '删除',
    icon: createVNode(ExclamationCircleFilled, {
      style: {
        color: 'var(--color--danger)'
      }
    }),
    content: '确定删除该表单么',
    okText: '确定',
    okButtonProps: {
      danger: true,
      type: 'primary'
    },
    cancelText: '取消',
    onOk() {
      console.log('OK')
      TemplateQuestionDel(item.id).then(() => {
        message.success('删除成功')
        getList()
        init()
      })
    },
    onCancel() {
      console.log('Cancel')
    }
  })
}

const modal2Cancel = () => {
  // modelForm.value?.clearValidate()
  const obj = _.cloneDeep(formData.value)

  modal2.open = false
  formRef.value?.init(obj)
  // obj.content.map((w) => {
  //   w.list.map((v) => {
  //     if (v.type.includes('+输入')) {
  //       v.options.find((u) => {
  //         if (u.input) {
  //           u.disabled = true
  //           return true
  //         }
  //       })
  //     }
  //   })
  // })
  // Object.assign(formState, obj)
  // modal2.open = false
  // modal.title = '编辑健康随访'
  // modal.type = 'update'
  // modal.open = true
}

const convert = (content, flag) => {
  if (flag) {
    return content.map((v) => {
      v.list = v.list.map((w) => {
        if (w.type.includes('选')) {
          w.options.map((u, index) => {
            u.sort = sorts[index]
          })
        }

        return {
          id: w.id,
          questionName: w.name,
          questionType: w.type,
          sort: w.sort,
          inputText: w.inputText,
          inputMode: w.inputMode,
          rules: w.rules,
          config: w.config,
          options: w.options,
          value: w.value,
          showCondition: w.showCondition,
          exc: w.exc
        }
      })
      return v
    })
  } else {
    return content.map((v) => {
      v.list = v.list.map((w) => {
        // if (w.questionType.includes('选')) {
        //   w.options.map(     (u, index) => {
        //     delete u.sort
        //   })
        // }

        return {
          id: w.id,
          name: w.questionName,
          type: w.questionType,
          sort: w.sort,
          inputText: w.inputText,
          inputMode: w.inputMode,
          rules: w.rules,
          config: w.config,
          options: w.options,
          value: w.value,
          showCondition: w.showCondition || null,
          exc: w.exc
        }
      })
      return v
    })
  }
}

// const modal4 = reactive({
//   title: '题目关联',
//   open: false
// })

// const showCondition = ref({
//   operator: 'AND',
//   conditions: [
//     {
//       id: '',
//       operator: '==',
//       value: ''
//     }
//   ]
// })

// const showConditionObj = ref({})

// const showConditionCurrent = ref()

// const showConditionModal = (item, index) => {
//   if (item.showCondition) {
//     showCondition.value = item.showCondition
//   } else {
//     showCondition.value = {
//       operator: 'AND',
//       conditions: [
//         {
//           id: '',
//           operator: '==',
//           value: ''
//         }
//       ]
//     }
//   }
//
//   modelForm4.value?.clearValidate()
//   showConditionCurrent.value = index
//
//   modal4.open = true
// }

// const showConditionDel = (item) => {
//   Modal.confirm({
//     title: '删除',
//     icon: createVNode(ExclamationCircleFilled, {
//       style: {
//         color: 'var(--color--danger)'
//       }
//     }),
//     content: '确定删除题目关联吗？',
//     okText: '确定',
//     okButtonProps: {
//       danger: true,
//       type: 'primary'
//     },
//     cancelText: '取消',
//     onOk() {
//       console.log('OK')
//       item.showCondition = null
//       modal3.type = 'modify'
//     },
//     onCancel() {
//       console.log('Cancel')
//     }
//   })
// }
//
// const conditionsAdd = (list) => {
//   list.push({
//     id: '',
//     operator: '==',
//     value: ''
//   })
// }
//
// const conditionsDel = (i, list) => {
//   list.splice(i, 1)
// }

// const modelForm4 = ref(null)
//
// const conditionsChange = (type, c) => {
//   if (type === '输入') {
//     c.operator = '填写完成'
//     c.value = ''
//   } else {
//     c.operator = '=='
//     c.value = ''
//   }
// }
//
// const operatorChange = (e, c) => {
//   console.log(e)
//   if (e === '填写完成') {
//     c.value = ''
//   }
// }
//
// const modal4Confirm = () => {
//   modelForm4.value.validate().then(() => {
//     // 验证通过
//     formData.value.content[showConditionCurrent.value[0]].list[
//       showConditionCurrent.value[1]
//     ].showCondition = showCondition.value
//
//     modal3.type = 'modify'
//     modal4.open = false
//   })
// }
</script>

<style lang="less" scoped>
@import './index.less';
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}

input[type='number'] {
  -moz-appearance: textfield;
}
.header {
  flex: 0 0 auto;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  .left {
    ::v-deep(.ant-space-item) {
      display: flex;
      flex-direction: row;
      align-items: center;
    }
    .title {
      font-size: 14px;
      font-family:
        PingFang SC,
        PingFang SC;
      font-weight: 400;
      color: #4e5969;
      line-height: 32px;
    }
  }
  .right {
    ::v-deep(.ant-space-item) {
      display: flex;
      flex-direction: row-reverse;
      align-items: center;
    }
  }
}
.main {
  flex: 1 1 auto;
  margin-top: 16px;
  overflow: hidden auto;
  :deep(.ant-table-wrapper) {
    .ant-table-cell {
      p {
        white-space: normal;
        margin-bottom: 0;
        .configuration {
          color: #3491fa;
          background: #e8f7ff;
          border-color: #3491fa;
          display: inline-block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 100%;
          margin-top: 10px;
          &:nth-child(1) {
            margin-top: 0;
          }
        }
        .success {
          color: #00b42a;
          background: #e8ffea;
          border-color: #00b42a;
          display: inline-block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 100%;
          margin-top: 10px;
          &:nth-child(1) {
            margin-top: 0;
          }
        }
        .groupTag {
          display: inline-block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 100%;
          margin-top: 10px;
          margin-right: 10px;
          &:nth-child(1) {
            margin-top: 0;
          }
        }
      }
    }
  }
}
.input {
  width: 210px !important;
}
</style>
